#!/usr/bin/python3
import sys
import os
import subprocess
linking = '-c' not in sys.argv and '-S' not in sys.argv and '-E' not in sys.argv
args = sys.argv[1:]

args += '-g -pthread'.split()
srcdir = os.path.dirname(os.path.dirname(__file__))
if linking:
    is_shared = '-shared' in args
    if not is_shared: # don't link the runtime into .so's - only into the executables using them
        args += [os.path.join(srcdir, f) for f in ['funtrace.cpp', 'funtrace_pg.S']] + [f'-Wl,--dynamic-list={srcdir}/funtrace.dyn']
    else:
        # remove no-undefined - __return__ will be undefined in shared objects and so will the funtrace_* runtime functions
        args = [a for a in args if a != '-Wl,--no-undefined']
    args += ['-ldl']
    # note that we don't pass -pg when linking (and therefore the -mfentry and -minstrument-return-call
    # flags which do nothing without -pg.) this is to avoid the generation of gmon.out. the downside
    # is that if .cpp files are passed to the linker (so compiling and linking in a single command),
    # we won't instrument those files. proper build system integration is ofc better than this wrapper...
else:
    args += '-pg -mfentry -minstrument-return=call'.split()

funtracexx = os.path.join(srcdir, 'compiler-wrappers/funtrace++')
os.execl(funtracexx, *([funtracexx, 'g++'] + args))
